var gallery = liwe.module ( "gallery" );

gallery.init = function ()
{
	gallery.load_templates ();
};

gallery._parse_images = function ( dest_div, wwl_name, data )
{
	if ( data.items.count () < 1 ) return;
	console.debug ( data );
	var thumb, img, fname, fid, title;
	var path = data.image_path;
	var thumb_path = data.thumb_path;
	var g = new WWL.gallery ( wwl_name );
	g.set_thumb_size ( data.thumb_size.w, data.thumb_size.h );
	data.items.iterate ( function ( v )
				{
					//fname = v.name + v.ext;
					title = v.title;
					fid = v.id + v.ext
					img = path + '/' + fid; 
					thumb = thumb_path + '/' + fid;
					//console.debug ( img );
					g.add_item ( img, title, v.descr, thumb );
				} );
	g.render ( dest_div );
};

gallery.create = function ( dest_div, gal, wwl_name, cback )
{
	var vals = {};
	vals [ 'action' ] = 'gallery.ajax.list_imgs';
	vals [ 'id_gal' ] = ( parseInt ( gal, 10 ) ) ? gal : '';
	vals [ 'gal_name' ] = ( ! parseInt ( gal, 10 ) ) ? gal : '';

	gallery.ajax ( vals , function ( data ) 
				{
					if ( data.get ( 'items', [] ).count () < 1 )
					{
						if ( cback ) cback ();
						return;
					}
					gallery._parse_images ( dest_div, wwl_name, data );
				} ); 
};

gallery._gallery_box = function ( dest_div, wwl_name, json_data )
{
	if ( document.readyState !== "complete" ) 
	{ 
		setTimeout ( function () 
				{
					gallery._gallery_box ( dest_div, wwl_name, json_data );
				}, 200 );
	}
	var data = json_data.parseJSON ();	
	gallery._parse_images ( dest_div, wwl_name, data );
};

gallery.plugin = function ( div, params )
{
	div.style.width = params [ 'width' ] + 'px';
	div.style.height = params [ 'height' ] + 'px';

	gallery.create ( div, params [ 'name' ], "plugin:wwl:" + params [ 'name' ], function () 
			{ 
				div.style.display = 'none' 
				console.error ( 'gallery.plugin: gallery %s doesn\'t exists!', params [ 'name' ] );
			} );
};
